package com.eshealthy.controller;

import com.eshealthy.entity.*;
import com.eshealthy.service.DoctorService;
import com.eshealthy.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("doctor")
@Slf4j
public class DoctorController {
    @Autowired
    private DoctorService doctorService;

//    全文检索
    @GetMapping("search")
    public Map<String,Object>search(Integer id,String word,Integer page,Integer rows) throws IOException {
        log.info(id+word);
        HashMap<String,Object> map=new HashMap<>();
        page = page == null ? 1 : page;
        rows = rows == null ? 4 : rows;
        if (id==1){
            List<Drug> drugs= doctorService.searchDrug(page,rows,word);
            Integer totals = (int)doctorService.Totals(id,word);
            Integer totalsPage = totals % rows == 0 ? totals / rows : totals / rows + 1;
            map.put("drugs", drugs);
            map.put("totals", totals);
            map.put("totalPage", totalsPage);
            map.put("page", page);
        }else if(id==2){
            List<MedicalDevice> devices= doctorService.searchDevice(page,rows,word);
            Integer totals = (int)doctorService.Totals(id,word);
            Integer totalsPage = totals % rows == 0 ? totals / rows : totals / rows + 1;
            map.put("devices", devices);
            map.put("totals", totals);
            map.put("totalPage", totalsPage);
            map.put("page", page);
        }else {
            List<Library> libraries= doctorService.searchLibrary(page,rows,word);
            Integer totals = (int)doctorService.Totals(id,word);
            Integer totalsPage = totals % rows == 0 ? totals / rows : totals / rows + 1;
            map.put("libraries", libraries);
            map.put("totals", totals);
            map.put("totalPage", totalsPage);
            map.put("page", page);
        }


        return map;
    }
    /*坐诊时间表
    * */
    @GetMapping("findTime")
    public Map<String,Object> findTime(String aid){
        HashMap<String,Object> map=new HashMap<>();

        int j=0;
        int[]t=doctorService.week();
        List<Scheduling> schedulings= doctorService.findTime(aid,"Friday");
        String[][] time = new String[schedulings.size()][7];
        for(int i=0;i<schedulings.size();i++){
           for(int l=0;l<7;l++){
               if(t[l]==1){
                   time[i][j]=schedulings.get(i).getMonday();j+=1;
               }else if(t[l]==2){
                   time[i][j]=schedulings.get(i).getTuesday();j+=1;
               }else if(t[l]==3){
                   time[i][j]=schedulings.get(i).getWednesday();j+=1;
               }else if(t[l]==4){
                   time[i][j]=schedulings.get(i).getThursday();j+=1;
               }else if(t[l]==5){
                   time[i][j]=schedulings.get(i).getFriday();j+=1;
               }else if(t[l]==6){
                   time[i][j]=schedulings.get(i).getSaturday();j+=1;
               }else{
                   time[i][j]=schedulings.get(i).getSunday();j+=1;
               }
           }j=0;

        }
        j=0;
        for(int i=0;i<schedulings.size();i++){
            schedulings.get(i).setMonday(time[i][j]);j+=1;
            schedulings.get(i).setTuesday(time[i][j]);j+=1;
            schedulings.get(i).setWednesday(time[i][j]);j+=1;
            schedulings.get(i).setThursday(time[i][j]);j+=1;
            schedulings.get(i).setFriday(time[i][j]);j+=1;
            schedulings.get(i).setSaturday(time[i][j]);j+=1;
            schedulings.get(i).setSunday(time[i][j]);j=0;
        }

        map.put("schedulings",schedulings);
        return map;
    }
    /*
    * 登录
    * */
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody Doctor doctor){
        log.info("当前登录的用户信息："+doctor.toString());

        Map<String, Object>map = new HashMap<>();
        try{
            Doctor doctorDB =doctorService.login(doctor);
            Map<String,String> payload=new HashMap<>();
            payload.put("id",doctorDB.getId());
            payload.put("name",doctorDB.getName());
            String token= JWTUtils.getToken(payload);
            doctorDB.setPassword("");
            doctorDB.setName("");
            map.put("token",token);
            map.put("state",true);
            map.put("msg","用户登录成功");
            map.put("doctor",doctorDB);
        }catch(Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","输入错误，请重新登录");
        }
        return map;
    }
/*
* 查询坐诊时间表*/

    @GetMapping("appointment")
    public Map<String,Object> appointment(Integer id,Integer page,Integer rows){
        log.info("查询信息"+id+page+rows);
        page = page==null?1:page;
        rows = rows==null?7:rows;
        HashMap<String,Object> map=new HashMap<>();
        List<Patient> appointments= doctorService.findSchedule(id,page,rows);
        map.put("appointments",appointments);

        Integer totals=doctorService.findTotalsSchedule(id);
        Integer totalsPage=totals%rows==0?totals/rows:totals/rows+1;
        map.put("totals",totals);
        map.put("totalPage",totalsPage);
        map.put("page",page);
        return map;
    }
    /*
    * 查询一条出诊时间*/
    @GetMapping("appointmentOne")
    public Map<String,Object> appointmentOne(Integer id){
        log.info("查询信息"+id);
        HashMap<String,Object> map=new HashMap<>();
        Patient patient= doctorService.findOne(id);
        map.put("patient",patient);
        return map;
    }
    /*
    * 添加病例*/
    @PostMapping("diagnosis")
    public Map<String,Object> diagnosis(Integer id,@RequestBody Cases cases)throws IOException {
        log.info(String.valueOf(cases)+id);
        doctorService.updateStatus(id);
        cases.setId(doctorService.findPid(id));
        cases.setDepartment(doctorService.check(id).getDepartment());
        cases.setDoctor_name(doctorService.check(id).getName());
        cases.setPatient_name(doctorService.pname(id));
        cases.setTime(new SimpleDateFormat("yyyy-HH-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
        cases.setAdvice("您需要做"+cases.getItem()+"项目检查\n"+"你还需要吃"+cases.getDrug()+"药物");
        doctorService.addCase(cases);
        HashMap<String,Object> map=new HashMap<>();
//        List<Scheduling> schedulings= doctorService.findTime(aid);
        map.put("msg","保存成功");
        return map;
    }
    @GetMapping("findCase")
    public Map<String,Object>findCase(Integer page, Integer rows) throws IOException {
    page = page == null ? 1 : page;
    rows = rows == null ? 4 : rows;
    HashMap<String, Object> map = new HashMap<>();
    List<Cases> cases = doctorService.findCases(page, rows);
    Integer totals = (int)doctorService.findTotalsCase();
//        System.out.println(totals);
    Integer totalsPage = totals % rows == 0 ? totals / rows : totals / rows + 1;
    map.put("cases", cases);
    map.put("totals", totals);
    map.put("totalPage", totalsPage);
    map.put("page", page);
    return map;
}
    /*
     * 注册
     * */
    @PostMapping("register")
    public Map<String,Object> register(@RequestBody Doctor doctor, String code, HttpServletRequest request){
        log.info("用户输入的信息[{}]"+doctor.toString());
        log.info("用户输入的验证码信息[{}]"+code);
        Map<String,Object> map = new HashMap<>();
        try{
            String key = (String) request.getServletContext().getAttribute("code"); //正确验证码
            if(key.equalsIgnoreCase(code)){
                doctorService.register(doctor);
                doctorService.registerArea(doctor.getArea());
                map.put("state",true);
                map.put("msg","注册成功");
            }else{
                throw new RuntimeException("验证码错误");
            }
        }
        catch(Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","提示："+e.getMessage());
        }
        return map;
    }
}
